package com.xbh.realtime.tio.messageQueue;

import com.xbh.realtime.tio.websocket.MyWSConfig;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.websocket.common.WsResponse;
import redis.clients.jedis.JedisPubSub;

import java.util.Map;
import java.util.function.Consumer;

/**
 * @TioChannel: 建立一个 频道 用来 被订阅
 * @author: ZBoHang
 * @time: 2021/8/11 15:41
 */
public class TioSubscriber extends JedisPubSub {

    private Map<String, ChannelContext> channelContextMap;

    public TioSubscriber(Map<String, ChannelContext> channelContextMap) {
        this.channelContextMap = channelContextMap;
    }

    @Override
    public void onMessage(String channel, String message) {
        System.out.println(channel + "----->>>" + message);

        channelContextMap.entrySet().forEach(new Consumer<Map.Entry<String, ChannelContext>>() {
            @Override
            public void accept(Map.Entry<String, ChannelContext> longChannelContextEntry) {
                // String serverId = longChannelContextEntry.getKey();
                ChannelContext channelContext = longChannelContextEntry.getValue();
                WsResponse wsResponse = WsResponse.fromText(message, MyWSConfig.characterPattern);
                Tio.send(channelContext, wsResponse);
            }
        });
    }

    @Override
    public void onSubscribe(String channel, int subscribedChannels) {
        System.out.println("-->订阅 TioChannel success");
    }

    @Override
    public void onUnsubscribe(String channel, int subscribedChannels) {
        System.out.println("-->取关 TioChannel success");
    }
}
